
public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int size = 0;
        int len = 0;
        ListNode pos = head;
        ListNode cur = head;
        if(head == null){
            return null;
        }
        while(pos != null){
            pos = pos.next;
            size++;
        }
        if(n > size || n < 1){
            return head.next;
        }
        len = size - n;
        ListNode prev = cur;
        while(len != 0){
            prev = cur;
            cur = cur.next;
            len--;
        }
        if(prev == cur){
            head = head.next;
        }else{
            prev.next = cur.next;
        }
        return head;
    }
}